package com.demo.juc.unsafe;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * @ClassName SimpleDateFormatUnsafe
 * @Author bsy
 * @Description 模拟高并发场景SimpleDateFormat线程非安全
 * @Date 2022/10/1 11:04
 * @Version 1.0
 */
public class SimpleDateFormatUnsafe {

    private static final int COUNT_DOWN_LATCH = 1000;
    private static final int COUNT_SEMAPHORE = 20;

    private static SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

    public static void main(String[] args) throws ParseException, InterruptedException {

        CountDownLatch countDownLatch = new CountDownLatch(COUNT_DOWN_LATCH);
        Semaphore semaphore = new Semaphore(COUNT_SEMAPHORE);

        ExecutorService threadPool = Executors.newCachedThreadPool();
        try {
            for (int i = 0; i < COUNT_DOWN_LATCH; i++) {
                threadPool.execute(() -> {
                    try {
                        semaphore.acquire();
                        dateFormat.parse("2022-10-01");
                        semaphore.release();
                        countDownLatch.countDown();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                });
            }

        } catch (Exception ex) {
            ex.printStackTrace();
            System.out.println("日期处理异常：" + ex.getCause() + ex.getMessage());
        } finally {
            countDownLatch.await();
            threadPool.shutdown();
        }
    }
}
